//
//  BaseTableView.m
//  公考神器
//
//  Created by 毕武侠 on 16/3/10.
//  Copyright © 2016年 毕武侠. All rights reserved.
//

#import "BaseTableView.h"
#import "BaseTableViewCell.h"
#import "UIScrollView+EmptyDataSet.h"

@interface BaseTableView () <UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, cellActionDelegate>

@property (nonatomic, assign) NSUInteger pageNumber;
@property (nonatomic, assign) BOOL notReusable;
@property (nonatomic, getter=isLoading) BOOL loading;
@property (nonatomic, assign) BOOL isLoadNew;

@end

@implementation BaseTableView

- (void)initstance {
    self.delegate = self;
    self.dataSource = self;
    self.emptyDataSetSource = self;
    self.emptyDataSetDelegate = self;
    
    self.showLoadingImage = YES;
    self.showDefaultImage = YES;
    self.pageNumber = 1;
    self.backgroundColor = [UIColor whiteColor];
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)initCellClass:(NSString *)cellClassName cellIdentifier:(NSString *)identifier {
    [self initstance];
    
    self.cellClassName = cellClassName;
    self.identifier = identifier;
}

- (void)registerCellClass:(NSString *)cellClassName cellIdentifier:(NSString *)identifier {
    [self initstance];
    
    [self registerNib:[UINib nibWithNibName:cellClassName bundle:nil]
         forCellReuseIdentifier:identifier];
    
    self.cellClassName = cellClassName;
    self.identifier = identifier;
}

- (void)setCellClass:(NSString *)cellClassName cellIdentifier:(NSString *)identifier {
    [self initstance];
    self.cellClassName = cellClassName;
    self.identifier = identifier;
    self.notReusable = YES;
}
- (void)initRefreshViewNoFooter:(NSString *)modelClass{
    self.modelClass = modelClass;
    self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNumber = 0;
        [self loadData];
    }];
}
- (void)initRefreshView:(NSString *)modelClass {
    self.modelClass = modelClass;
    self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNumber = 0;
        [self loadData];
    }];
    self.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.mj_footer.automaticallyHidden = YES;
    self.mj_footer.automaticallyChangeAlpha = YES;
}

- (void)setSourceData:(NSMutableArray *)sourceData {
    _sourceData = sourceData;
    
    [self reloadData];
    if (sourceData.count == 0) {
        if (self.title.length == 0) {
            self.title = @"暂无数据";
        }
        [self reloadEmptyDataSet];
    }
}

- (void)setLoading:(BOOL)loading {
    if (self.isLoading == loading) {
        return;
    }
    
    _loading = loading;
    [self reloadEmptyDataSet];
}

- (void)setUrl:(NSString *)url {
    _url = url ? [NSString stringWithFormat:@"%@%@",[OtherNetworking sharedManager].STRURL, url] : [OtherNetworking sharedManager].STRURL;
}

- (NSString *)title {
    if (!_title) {
        _title = @"";
    }
    return _title;
}

- (NSString *)message {
    if (!_message) {
        _message = @"";
    }
    return _message;
}

- (void)refreshView {
    [self reloadData];
    if (_sourceData.count == 0) {
        if (self.title.length == 0) {
            self.title = @"暂无数据";
        }
        [self reloadEmptyDataSet];
    }
}

#pragma mark - tableView delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sourceData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseModel *model = self.sourceData[indexPath.row];
    return model.rowHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.identifier];
    if (!cell) {
        if (self.notReusable == YES) {
            cell = [[[NSBundle mainBundle] loadNibNamed:self.cellClassName owner:self options:nil] lastObject];
        } else {
            cell = [[BaseTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:self.identifier];
        }
    }
    
    cell.indexPath = indexPath;
    cell.actionDelegate = self;
    cell.data = self.data;
    BaseModel *model = self.sourceData[indexPath.row];
    [cell bindModel:model];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.editing == NO) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }

    if ([self.cellDelegate respondsToSelector:@selector(tableView:didselectIndexPath:)]) {
        [self.cellDelegate tableView:self didselectIndexPath:indexPath];
    }
}

#pragma mark - cell Action

- (void)actionIndexPath:(NSIndexPath *)indexPath infoData:(id)data {
    if ([self.cellDelegate respondsToSelector:@selector(tableView:didActionIndexPath:infoData:)]) {
        [self.cellDelegate tableView:self didActionIndexPath:indexPath infoData:data];
    }
}

#pragma mark - load Data

- (NSString *)modelClass {
    if (!_modelClass) {
        _modelClass = @"BaseModel";
    }
    return _modelClass;
}

- (void)loadData {
    if (!self.url || !self.parameter) {
        [self.mj_header endRefreshing];
        return;
    }
    
    [self.mj_footer endRefreshing];
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.sgbody.data];
    data[@"page"] = [NSString stringWithFormat:@"%ld", self.pageNumber];
    self.parameter.sgbody.data = data;
    
    [SGHttpTool POST:self.url parameter:self.parameter sucess:^(id result) {
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 2000) {
            if ([receive.data count] > 0) {
                self.pageNumber = 1;
                [self.sourceData removeAllObjects];
                self.sourceData = receive.data;
            }
        }
        [self.mj_header endRefreshing];
    } failure:^(id reslut) {
        [self.mj_header endRefreshing];
    }];
}

- (void)loadMoreData {
    if (!self.url || !self.parameter) {
        [self.mj_footer endRefreshing];
        return;
    }
    
    if (self.pageNumber <= 0) {
        self.pageNumber++;
    }
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.sgbody.data];
    data[@"page"] = [NSString stringWithFormat:@"%ld", self.pageNumber];
    self.parameter.sgbody.data = data;
    
    [SGHttpTool POST:self.url parameter:self.parameter sucess:^(id result) {
//        NSLog(@"result = %@", result);
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 2000) {
            if ([receive.data count] > 0) {
                self.pageNumber++;
                [self.sourceData addObjectsFromArray:receive.data];
                [self reloadData];
                [self.mj_footer endRefreshing];
            } else {
                [self.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            [self.mj_footer endRefreshing];
        }
        
    } failure:^(id reslut) {
        [self.mj_footer endRefreshing];
    }];
}

- (void)reloadNewData {
    if (!self.url || !self.parameter) {
        [self.mj_header endRefreshing];
        self.loading = NO;
        if (self.sourceData.count == 0) {
            self.title = @"暂无数据";
            [self reloadEmptyDataSet];
        }
        return;
    }
    
    self.isLoadNew = self.loading = YES;
    self.pageNumber = 0;
    NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary: self.parameter.sgbody.data];
    data[@"page"] = [NSString stringWithFormat:@"%ld", self.pageNumber];
    self.parameter.sgbody.data = data;
    
    [SGHttpTool POST:self.url parameter:self.parameter sucess:^(id result) {
        self.isLoadNew = self.loading = NO;
        SGReceive *receive = [SGReceive receiveWithResponseObject:result dataClass:NSClassFromString(self.modelClass)];
        if ([receive.code intValue] == 2000) {
            
            NSLog(@"??????????????????%@",[receive.data mj_keyValues]);

            if ([receive.data count] > 0) {
                self.pageNumber = 1;
                [self.sourceData removeAllObjects];
                
                [self setContentOffset:CGPointMake(0,0) animated:YES];
                if ([self.cellDelegate respondsToSelector:@selector(tableView:loadDataAtIndex:)]) {
                    _sourceData = receive.data;
                    [self.cellDelegate tableView:self loadDataAtIndex:self.pageNumber - 1];
                } else {
                    self.sourceData = receive.data;
                }
            } else {
                if (self.sourceData.count > 0) {
                    [self.sourceData removeAllObjects];
                    [self reloadData];
                }
                self.title = @"暂无数据";
                [self reloadEmptyDataSet];
            }
        } else {
            if (self.sourceData.count == 0) {
                self.title = @"暂无数据";
                [self reloadEmptyDataSet];
            }
        }
        [self.mj_header endRefreshing];
    } failure:^(id reslut) {
//        NSLog(@"%@", reslut);
        self.isLoadNew = self.loading = NO;
        [self.mj_header endRefreshing];
        if (self.sourceData.count == 0) {
            self.title = NoNetWorkMessage;
            [self reloadEmptyDataSet];
        }
    }];
}

- (void)showEmptyView {
    [self reloadEmptyDataSet];
}

#pragma mark - DZNEmptyDataSetSource Methods

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = nil;
    UIFont *font = nil;
    UIColor *textColor = nil;
    
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    text = self.title;
    font = [UIFont systemFontOfSize:17.0];
    textColor = [UIColor grayColor];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *name = [self loadImageName];
    return name ? [UIImage imageNamed:name] : nil;
}

- (NSString *)loadImageName {
    if (self.isLoading == YES) {
        return self.showLoadingImage == YES ? @"loading_imgBlue" : nil;
    } else {
        return self.showDefaultImage == YES ? IMG_EmptyDefault : nil;
    }
}

- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0) ];
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor whiteColor];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -(SCREEN_HEIGHT / 6);
}

- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView {
    return 0.0;
}

#pragma mark - DZNEmptyDataSetDelegate Methods

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return NO;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

// YES: 开始转圈
- (BOOL)emptyDataSetShouldAnimateImageView:(UIScrollView *)scrollView {
    return self.isLoading;
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    if (self.isLoading) {
        return;
    }
    
    self.loading = YES;
    [self reloadNewData];
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    if (self.isLoading) {
        return;
    }
    
    self.loading = YES;
    [self reloadNewData];
}

@end
